<template>

    <div class="addGoodsBox" v-loading="loading">

        <el-form ref="form">
            <el-form-item label="商品名称">
                <el-input v-model="initial_data.name" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="商品简介">
                <el-input v-model="initial_data.slogan" style="width:300px"></el-input>
            </el-form-item>


            <el-form-item label="出价">
                <el-input v-model="initial_data.selling_price" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="进价">
                <el-input v-model="initial_data.purchase_price" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="原价">
                <el-input v-model="initial_data.original_price" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="库存">
                <el-input v-model="initial_data.stock" style="width:300px"></el-input>
            </el-form-item>

            <el-form-item label="分类">
                <el-select v-model="initial_data.classify_id" style="width:300px" placeholder="请选择分类">
                    <el-option v-for="(item) in classifyList" :key="item.id" :label="item.name"
                               :value="item.id"></el-option>
                </el-select>
            </el-form-item>


        </el-form>

        <!-- 编辑器 -->
        <div class="pictures">
            <span class="title">商品详情</span>
            <div class="editorBox">
                <div id="toorbar" class="toolbar">
                </div>
                <div></div>
                <div id="editBox" class="editBox">
                    <div v-html="initial_data.detail"></div>
                </div>
            </div>
        </div>


        <div class="pictures">
            <span class="title">商品缩略图</span>
            <div class="picUpload">
                <div>
                    <el-upload
                            :http-request="handlePictureCardPreview"
                            :multiple="false"
                            action=""
                            name="add_business_thumbnails"
                            list-type="picture-card"
                    >
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog
                            :modal="false"
                            :center="true"
                            :show-close="false"
                            class="commonVisible"
                            :visible.sync="businesstThumbnailsVisible"
                            :fullscreen="true">
                        <img alt="" class="" :src="initial_data.thumbnail">
                    </el-dialog>


                </div>
            </div>
        </div>

        <div class="pictures">
            <span class="title">商品图片</span>
            <div class="">
                <div>
                    <el-upload
                            :http-request="handlePictureCardPreview"
                            :multiple="false"
                            action=""
                            name="add_goods_picture"
                            list-type="picture-card"
                    >
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="businesstThumbnailsVisible">
                        <img width="100%" :src="initial_data.thumbnail" alt="">
                    </el-dialog>
                </div>
            </div>
        </div>

        <div class="pictures">
            <span class="title">团购</span>
            <div style="margin-top: 10px">
                <el-switch
                        @change="changeGroupBy"
                        style="display: block"
                        v-model="initial_data.is_group"
                        active-text="参与"
                        inactive-text="不参与">
                </el-switch>
            </div>
        </div>

        <div class="pictures" v-if="groupVisible">
            <span class="title">团购人数</span>
            <el-input v-model="initial_data.people" style="width:300px">
            </el-input>
        </div>

        <div class="pictures">
            <span class="title">秒杀</span>
            <div style="margin-top: 10px">
                <el-switch
                        @change="changeSpike"
                        style="display: block"
                        v-model="initial_data.is_spike"
                        active-text="参与"
                        inactive-text="不参与">
                </el-switch>
            </div>
        </div>

        <div class="pictures" v-if="spikeVisible">
            <span class="title">秒杀价格</span>
            <el-input v-model="initial_data.spike_selling_price" style="width:300px">
            </el-input>
        </div>

        <div class="pictures" v-if="spikeVisible">
            <span class="title">秒杀日期</span>
            <el-date-picker
                    value-format="yyyy-MM-dd"
                    style="width:400px"
                    v-model="initial_data.day"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
            </el-date-picker>
        </div>

        <div class="pictures" v-if="spikeVisible">
            <span class="title">秒杀时间</span>
            <el-select @change="getHourName" multiple style="width: 300px" v-model="initial_data.hour" placeholder="请选择">
                <el-option

                        v-for="item in spikeTime"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
            </el-select>
        </div>


        <shelfGoods
                @updateEnable_sku="updateEnable_sku"
                :skuData="getskuData"
                :checked="initial_data.enable_sku"
                @setSkuData="setSkuData">

        </shelfGoods>

        <div class="submitBtnBox">
            <el-button class="submitBtn" @click="submitFn" type="primary">确认添加</el-button>
        </div>

    </div>
</template>

<script>
    import E from 'wangeditor'
    import shelfGoods from '@/layout/components/shelf-goods'

    var editor = new E('#toorbar', '#editBox');
    const _ = require('lodash');
    export default {
        name: 'Add-goods',
        components: {shelfGoods},
        data() {
            return {
                loading: false,
                list: null,
                businesstThumbnailsVisible: true,
                classifyList: [],
                statusOption: [{
                    id: 0,
                    name: '待审核'
                },
                    {
                        id: 1,
                        name: '下架'
                    },
                    {
                        id: 2,
                        name: '上架'
                    }],
                getskuData: '',
                initial_data: {
                    token: localStorage.getItem('user_token'),//token
                    stores_id: localStorage.getItem('user_store_id') ?  localStorage.getItem('user_store_id') : 0,
                    name: '',//商品名称
                    slogan: '',//商品简介
                    thumbnail: '',//商品缩略图
                    selling_price: '',//售价
                    purchase_price: '',//进价
                    original_price: '',//原价
                    detail: '',//富文本编辑器
                    classify_id: '',//分类名称
                    status: 0,//商户状态
                    stock: '',//库存
                    images: [],//商品图片
                    sku_data: [],//规格项
                    sku: [],//商品规格表格内容
                    enable_sku: 0,
                    is_group: false,
                    is_spike: false
                },
                groupVisible: false, //团购
                spikeVisible: false, //秒杀
                spikeTime: [
                    {id: 1, name: '00:00'},
                    {id: 2, name: '06:00'},
                    {id: 3, name: '08:00'},
                    {id: 4, name: '10:00'},
                    {id: 5, name: '12:00'},
                ],
                hourData: []
            }
        },
        methods: {
            getClassifyFn() {//分类列表
                this.$http.post('/web/good/classify', {
                    'token': localStorage.getItem('user_token'),
                    'p_id': this.$route.query.id
                }).then((response) => {
                    if (response.data.status == 'success') {
                        this.classifyList = response.data.data;
                    }
                }).catch((error) => {
                    console.log('error:', error)
                })
            },
            handlePictureCardPreview(file) {//图片上传
                let imageFile = file.file;
                let formData = new FormData();

                formData.append("image", imageFile);
                formData.append("action", file.filename);
                this.loading = true;
                this.$http.post('/api/tool/ali/upload/image', formData).then((response) => {
                    if (file.filename == 'add_business_thumbnails') {//商户缩略图
                        this.initial_data.thumbnail = response.data.data;
                    }
                    if (file.filename == 'add_goods_picture') {//商品图片
                        this.initial_data.images.push(response.data.data)
                    }
                    this.loading = false;
                }).catch((error) => {
                    console.log('图片上传失败');
                })
            },
            submitFn() {
                if (this.initial_data.is_spike){
                    if (!this.initial_data.spike_selling_price) {
                        this.$message.warning('请填写秒杀价格');
                        return;
                    }
                    if (!this.initial_data.day) {
                        this.$message.warning('请选择秒杀日期');
                        return;
                    }
                    if (this.initial_data.hour.length < 1) {
                        this.$message.warning('请选择秒杀时间');
                        return;
                    }

                    if (this.initial_data.day[0] === this.initial_data.day[1]) {
                        var day = [this.initial_data.day[0]];
                    }else{
                        var day = this.getDate(this.initial_data.day[0],this.initial_data.day[1]);
                    }

                    var spikeDate = [];
                    for (var i = 0; i < day.length; i++){
                        spikeDate.push(day[i])
                    }

                    var spike = [];
                    for (var l = 0; l < spikeDate.length; l++){
                        for (var k = 0; k < this.hourData.length; k++) {
                            spike.push({
                                selling_price: this.initial_data.spike_selling_price,
                                day: spikeDate[l],
                                hour: this.hourData[k],
                            })
                        }
                    }
                    this.initial_data.spikeData = spike;
                }

                if (this.initial_data.is_group && !this.initial_data.people){
                    this.$message.warning('请填写团购人数');
                    return;
                }

                if (this.initial_data.sku.length < 1) {
                    delete this.initial_data.sku;
                }else{
                    this.initial_data.sku = JSON.stringify(this.initial_data.sku);
                }

                if (this.initial_data.sku_data.length < 1) {
                    delete this.initial_data.sku_data;
                }else{
                    this.initial_data.sku_data = JSON.stringify(this.initial_data.sku_data);
                }


                this.loading = true;
                this.$http.post('/web/good/add', this.initial_data).then((response) => {
                    if (response.data.status === 'success') {
                        this.$message.success('添加成功');
                        Object.assign(this.$data, this.$options.data())
                    }
                    this.initial_data.sku = [];
                    this.initial_data.sku_data = [];
                    this.loading = false;
                }).catch((error) => {
                    this.initial_data.sku = [];
                    this.initial_data.sku_data = [];
                    console.log('error:', error)
                    this.loading = false;
                })

            },
            setSkuData(val) {
                // sku_data
                let sku_data = [];
                val.levelcont.forEach((value, index) => {
                    let arr_cont = [];
                    let arr_thumbnail = [];
                    val.levellist[index].forEach((vallist, indexlist) => {
                        arr_cont.push(vallist.cont);
                        arr_thumbnail.push(vallist.thumbnail);
                    })
                    sku_data.push({
                        'sku': value,
                        'name': arr_cont,
                        'thumbnail': arr_thumbnail
                    })
                })
                this.initial_data.sku_data = sku_data;

                // sku
                if (val.finalData) {
                    let sku = [];
                    let sku_length = this.initial_data.sku_data.length;
                    let sku_value = [];
                    val.finalData.forEach((valuesku, indexsku) => {
                        sku_value.push({
                            'value': _.take(valuesku, sku_length),
                            'purchase_price': _.takeRight(valuesku, 4)[0],
                            'original_price': _.takeRight(valuesku, 4)[1],
                            'selling_price': _.takeRight(valuesku, 4)[2],
                            'stock': _.takeRight(valuesku, 4)[3]
                        })
                    })
                    this.initial_data.sku = sku_value;
                }
            },
            editorFn() {
                editor.customConfig.onchange = (html) => {
                    editor.txt.clear();
                    editor.txt.html(html);
                    this.initial_data.detail = html;
                }

                // 自定义菜单配置
                editor.customConfig.menus = [
                    'head',  // 标题
                    'bold',  // 粗体
                    'fontSize',  // 字号
                    'fontName',  // 字体
                    'underline',  // 下划线
                    'strikeThrough',  // 删除线
                    'foreColor',  // 文字颜色
                    'backColor',  // 背景颜色
                    'link',  // 插入链接
                    'list',  // 列表
                    'justify',  // 对齐方式
                    'image',  // 插入图片
                    'table',  // 表格
                    'undo',  // 撤销
                ]

                editor.customConfig.zIndex = 100;
                editor.customConfig.uploadImgShowBase64 = true
                editor.customConfig.showLinkImg = false

                //获取焦点
                var that = this;
                editor.create();
            },
            thumbnailDelete() {
                // console.log('缩略图删除');
                this.initial_data.thumbnail = '';
            },
            imagesDelete(val, index) {
                // console.log('商品图片删除');
                this.initial_data.images[index].image = '';
            },

            updateEnable_sku(value) {
                if (value.value === true) {
                    this.initial_data.enable_sku = 1;
                } else {
                    this.initial_data.enable_sku = 0;
                }
            },

            changeGroupBy(value) {
                this.groupVisible = value;
            },

            changeSpike(value) {
                this.spikeVisible = value;
            },

            getHourName(value){
                this.hourData = [];
                for (var l = 0; l < value.length; l++){
                    for (var i = 0; i < this.spikeTime.length; i++){
                        if (value[l] === this.spikeTime[i].id){
                            this.hourData.push(this.spikeTime[i].name);
                        }
                    }
                }
            },

            getDate(day1, day2) {
                var getDate = function (str) {
                    var tempDate = new Date();
                    var list = str.split("-");
                    tempDate.setFullYear(list[0]);
                    tempDate.setMonth(list[1] - 1);
                    tempDate.setDate(list[2]);
                    return tempDate;
                }
                var date1 = getDate(day1);
                var date2 = getDate(day2);
                if (date1 > date2) {
                    var tempDate = date1;
                    date1 = date2;
                    date2 = tempDate;
                }
                date1.setDate(date1.getDate() + 1);
                var dateArr = [];
                var i = 0;
                while (!(date1.getFullYear() === date2.getFullYear()
                    && date1.getMonth() === date2.getMonth() && date1.getDate() === date2
                        .getDate())) {
                    var dayStr = date1.getDate().toString();
                    if (dayStr.length === 1) {
                        dayStr = "0" + dayStr;
                    }
                    dateArr[i] = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-"
                        + dayStr;
                    i++;
                    date1.setDate(date1.getDate() + 1);
                }
                dateArr.splice(0, 0, day1)
                dateArr.push(day2);
                return dateArr;


            }
        },
        mounted() {
            this.getClassifyFn();
            this.editorFn();
        }
    }
</script>

<style scoped lang="scss">
    .submitBtnBox {
        text-align: right;
        margin-top: 30px;
    }

    .editorBox {
        width: 800px;
        border: 1px solid #ccc;

        .toolbar {
            background-color: #f7f6f6;
        }

        .editBox {
            height: 300px;
        }
    }

    .addGoodsBox {
        min-width: 1024px;
        margin: 40px;

        /deep/ .el-form-item__label {
            width: 100px;
            text-align: left;
        }

        .pictures {
            display: flex;
            flex-direction: row;
            font-size: 14px;
            color: #606266;
            line-height: 40px;
            font-weight: 700;
            margin-bottom: 30px;

            .title {
                width: 100px;
            }
        }

        .picUpload {
            position: relative;
            margin-right: 20px;
            width: 148px;

            /deep/ .el-dialog {
                box-shadow: none
            }

            /deep/ .el-upload-list__item {
                position: absolute;
                z-index: 4;
            }

            /deep/ .el-dialog__header, /deep/ .el-dialog__body {
                padding: 0
            }

            /deep/ .el-dialog.is-fullscreen {
                height: 148px;
            }

            /deep/ .el-dialog__body {
                display: flex;
                align-items: center;
            }

            .title {
                text-align: center;
                width: 100%;
                display: block;
                margin-top: 20px;
            }

            .commonVisible {
                // 				position:absolute;
                // 				left:0;
                // 				top:0;
                // 				width:100%;
                // 				height:100%;
                // 				overflow:hidden;

                // 				/deep/ .el-dialog__body{
                // 					display:flex;
                // 					align-items:center;
                // 					height:100%;
                // 					img{
                // 						width:100%;
                // 						display:block;
                // 					}
                // 				}
            }

            /deep/ .hoverBox {
                position: absolute;
                width: 100%;
                height: 100%;
                left: 0;
                top: 0;
                cursor: default;
                text-align: center;
                color: #fff;
                opacity: 1;
                font-size: 20px;
                background-color: rgba(0, 0, 0, .5);
                opacity: 0;
                // -webkit-transition: opacity .3s;
                // transition: opacity .3s;
                &:hover {
                    opacity: 1
                }

                /deep/ .deleteIcon {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    height: 100%;
                }
            }
        }


    }
</style>



